package com.yao;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * 限制只能输入正整数
 */
public class IntegerDocument extends PlainDocument {

    private static final long serialVersionUID = 1L;

    @Override
    public void insertString(int offs, String text, AttributeSet a) 
        throws BadLocationException, NumberFormatException {
        if (text == null) {
            return;
        }
        StringBuilder sbuiler = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            int code = text.codePointAt(0);
            if (code >= 48 && code <= 57) {
                sbuiler.append(text.charAt(i));
            }
        }
        super.insertString(offs, sbuiler.toString(), a);
    }
}
